package wk.asm;

import com.alibaba.fastjson.JSON;

import java.util.ArrayList;

/**
 * Created by wangkuan at 2018-08-31 10:10
 */
public class Starter {

    public static void main(String[] args) {
        new Starter().sortTest();
    }

    private void run() {
        Runtime runtime = Runtime.getRuntime();
        System.out.println("cpu核数:" + runtime.availableProcessors());
        System.out.println("freeMemory:" + (runtime.freeMemory() >> 20) + "M");
        System.out.println("maxMemory:" + (runtime.maxMemory() >> 30) + "G");
        System.out.println("totalMemory:" + (runtime.totalMemory() >> 20) + "M");
    }

    private void sortTest() {
        ArrayList<Order> list = new ArrayList<>();

        Order order1 = new Order();
        Order order2 = new Order();
        Order order3 = new Order();

        SubOrder subOrder10 = new SubOrder();
        subOrder10.setName("subOrder10");
        subOrder10.setPrice(2.0D);

        SubOrder subOrder11 = new SubOrder();
        subOrder11.setName("subOrder11");
        subOrder11.setPrice(1.0D);

        SubOrder subOrder20 = new SubOrder();
        subOrder20.setName("subOrder20");
        subOrder20.setPrice(3.0D);

        SubOrder subOrder21 = new SubOrder();
        subOrder21.setName("subOrder21");
        subOrder21.setPrice(14.0D);

        SubOrder subOrder30 = new SubOrder();
        subOrder30.setName("subOrder30");
        subOrder30.setPrice(14.0D);

        SubOrder subOrder31 = new SubOrder();
        subOrder31.setName("subOrder31");
        subOrder31.setPrice(13.0D);

        order1.setName("order1");
        order1.setPrice(20.01D);
        order1.getSubOrderList().add(subOrder10);
        order1.getSubOrderList().add(subOrder11);

        order2.setName("order2");
        order2.setPrice(120.00D);
        order2.getSubOrderList().add(subOrder20);
        order2.getSubOrderList().add(subOrder21);

        order3.setName("order3");
        order3.setPrice(56.00D);
        order3.getSubOrderList().add(subOrder30);
        order3.getSubOrderList().add(subOrder31);

        list.add(order1);
        list.add(order2);
        list.add(order3);

        list.sort((l1, l2) -> {
            initOrder(l1);
            initOrder(l2);

            return compare(l1.getMaxSubOrderPrice(), l2.getMaxSubOrderPrice());
        });

        System.out.println(JSON.toJSONString(list));
    }

    private void initOrder(Order order) {
        if (order.getMaxSubOrderPrice() == null) {
            order.setMaxSubOrderPrice(order.getSubOrderList().stream().mapToDouble(SubOrder::getPrice).max().orElse(0));
            order.getSubOrderList().sort((o1, o2) -> compare(o1.getPrice(), o2.getPrice()));
        }
    }

    private int compare(Double n1, Double n2) {
        if (n1 != null && n2 != null) {
            return n2 > n1 ? 1 : n2 < n1 ? -1 : 0;
        }

        return 0;
    }

}
